package com.keyinong.bluetooth;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.keyinong.qudan.R;
import com.keyinong.qudan.dapter.CaidanAdapter;
import com.keyinong.qudan.entity.GoodsInfoBean;
import com.keyinong.qudan.tools.HttpTools;
import com.keyinong.qudan.tools.Utility;
import com.loopj.android.http.JsonHttpResponseHandler;

public class BluetoothActivity extends Activity {
	private CaidanAdapter caidanAdapter;
	/**菜单列表*/
	private ListView lv;
    // Message types sent from the BluetoothService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    
    // Key names received from the BluetoothService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;

    // Name of the connected device
    private String mConnectedDeviceName = null;
    // String buffer for outgoing messages
//    private StringBuffer mOutStringBuffer;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the services
    public static BluetoothService mService = null;
    
    BluetoothPrintFormatUtil printFormatUtil = null;
    
	private EditText print_et;
	private RadioGroup radioGroup1;
	private RadioGroup radioGroup2;
	private String token;
	static int shuliang=0;
	private static Double zongjia=0.0;
	private TextView tv_shuliang;
	private TextView tv_zongjia;
	private TextView tv_content;
	private TextView tv_fee;
	private String orderno;
	private String order_time;
	private String receive_time;
	private String fee;
	private String recmode;
	private double heji;
	private String note;
	private ImageButton iv_back;
	private String address;
	private String shoushuofangshi="";
	private String total;
	private String name;
	private String phone;
	private String guige;
	private String dayno;
	private String aname;
	private String pname;
	private String off;
	private String more;
	private String youhuiquan;
	private String invoice;
	private String mcode;
	HttpTools httpTools=null;
	ArrayList<GoodsInfoBean> detaillist = new ArrayList<GoodsInfoBean>();
	
	LinkedHashMap<String, LinkedList<String>> menuMsgMap = new LinkedHashMap<String, LinkedList<String>>();

	LinkedList<String> gonds=new LinkedList<String>();
//	private RadioGroup radioGroup3;
    
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main1);
		address = getIntent().getStringExtra("address");
        zongjia=0.0;
		shuliang=0;
		orderDetail();
		lv=(ListView)findViewById(R.id.lv_caipin);
		tv_shuliang=(TextView)findViewById(R.id.tv_shuliang);
		tv_zongjia=(TextView)findViewById(R.id.tv_zongjia);
		tv_content=(TextView)findViewById(R.id.tv_content);
		tv_fee=(TextView)findViewById(R.id.tv_fee);
		iv_back=(ImageButton)findViewById(R.id.iv_back);
		iv_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		// Get local Bluetooth adapter
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		
		// If the adapter is null, then Bluetooth is not supported
		if (mBluetoothAdapter == null) {
			Toast.makeText(this, "您的设备不支持蓝牙", 0).show();
//			finish();
			return;
		}
		
		print_et = (EditText) findViewById(R.id.print_et);
		print_connect_btn = (Button) findViewById(R.id.print_connect_btn);
		radioGroup1 = (RadioGroup) findViewById(R.id.radioGroup1);
		radioGroup2 = (RadioGroup) findViewById(R.id.radioGroup2);
//		radioGroup3 = (RadioGroup) findViewById(R.id.radioGroup3);
		
		radioGroup1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.radio0:
					mService.printLeft();
					break;
				case R.id.radio1:
					mService.printCenter();
					break;
				case R.id.radio2:
					mService.printRight();
					break;
				}
			}
		});
		
		radioGroup2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.radio0:
					mService.printSize(0);
					break;
				case R.id.radio1:
					mService.printSize(1);
					break;
				case R.id.radio2:
					mService.printSize(2);
					break;
				}
			}
		});
		
	}
	
	private void orderDetail() {
		SharedPreferences sp = getSharedPreferences("spReg",
				Context.MODE_PRIVATE);
		token = sp.getString("token", "");
		String orderid = getIntent().getStringExtra("id");
//		TTs();
		if (httpTools == null) {
			httpTools = new HttpTools(BluetoothActivity.this);
		}
		httpTools.detail(token, orderid, new JsonOrderDetail());
	}
	
	private class JsonOrderDetail extends JsonHttpResponseHandler {
		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONObject response) {
			super.onSuccess(statusCode, headers, response);
			Log.e("lh", "JsonOrderDetail=="+response.toString());
			try {
				boolean code = response.getBoolean("code");
				if (code == true) {
					JSONObject object = response.getJSONObject("data");
					JSONArray array = object.getJSONArray("details");
					dayno = object.getString("dayno");
					orderno = object.getString("orderno");
					order_time = object.getString("order_time");
					receive_time = object.getString("receive_time");
					fee = object.getString("fee");
					note = object.getString("note");
					recmode = object.getString("recmode");
					total = object.getString("total");
					name = object.getString("name");
					phone = object.getString("phone");
					aname = object.getString("aname");
					pname = object.getString("pname");
					off = object.getString("off");
					more = object.getString("more");
					invoice=object.getString("invoice");
					mcode=object.getString("code");
					if(mcode.equals("null")){
						mcode="";
					}
					for (int i = 0; i < array.length(); i++) {
						JSONObject object2 = array.getJSONObject(i);
						String id = object2.getString("id");
						String name = object2.getString("name");
						String amount = object2.getString("amount");
						String price = object2.getString("price");
						String content = object2.getString("content");
						String sname = object2.getString("sname");
						shuliang +=Integer.parseInt(amount);
						zongjia= zongjia+Integer.parseInt(amount)*Double.parseDouble(price);
						heji = Double.parseDouble(total)+Double.parseDouble(fee);
						double jiage = Integer.parseInt(amount)*Double.parseDouble(price);
						detaillist.add(new GoodsInfoBean(name, amount, price, content,sname));
						if (sname.equals("null")||sname.equals("")) {
							guige="";
						}else {
							guige="("+sname+")";
						}
						gonds.add(" \n"+name+guige);
						gonds.add("*"+amount);
						gonds.add(""+jiage);
//						gonds.add(content+" - ");
					}
					if (off.equals("null")) {
						youhuiquan="";
					}else {
						youhuiquan="(满"+more+"减"+off+")";
					}
					if (pname.equals("null")) {
						pname="";
					}else {
						pname="("+pname+")";
					}
					if(note.equals("")||note.equals("null")){
						tv_content.setText("无");
						note="无";
					}else{
						tv_content.setText(note);
					}
					if(recmode.equals("1")){
						tv_fee.setVisibility(View.INVISIBLE);
						shoushuofangshi="店内自提";
					}else if (recmode.equals("2")) {
						tv_fee.setVisibility(View.VISIBLE);
						tv_fee.setText("(含运费￥"+fee+")");
						shoushuofangshi="送货上门";
					}else if (recmode.equals("3")){
						tv_fee.setVisibility(View.INVISIBLE);
						shoushuofangshi="堂吃";
					}
					if(fee.equals("0")){
						address="无";
					}
					tv_shuliang.setText(""+shuliang+"份");
					tv_zongjia.setText(""+heji+"元");
					
					caidanAdapter = new CaidanAdapter(getApplicationContext(), detaillist);
					lv.setAdapter(caidanAdapter);
					lv.setDivider(null);
					Utility.setListViewHeightBasedOnChildren(lv);
//						Log.i("zq", "list"+array.length());
				} else {
					String msg = response.getString("msg");
					Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				String responseBody, Throwable e) {
			super.onFailure(statusCode, headers, responseBody, e);
			Log.e("lh", "onFailure=="+responseBody);
		}
		
		

	}
	
	
    @Override
    public void onStart() {
        super.onStart();
        if (!mBluetoothAdapter.isEnabled()) {
        	//打开蓝牙
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        }
        if (mService==null) {
        	mService = new BluetoothService(this, mHandler);
        }
    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.option_menu, menu);
		return true;
	}
	
	
	public void onClick(View v){
		switch (v.getId()) {
		case R.id.print_btn:
			if (mService.getState() != BluetoothService.STATE_CONNECTED) {
				Toast.makeText(this, "蓝牙没有连接", Toast.LENGTH_SHORT).show();
//				return;
				Intent serverIntent = new Intent(this, DeviceListActivity.class);
		         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
			}
//			sendMessage(print_et.getText().toString()+"\n");
			sendMessage(printFormatUtil.printTitle("17度E")+"\n");
			sendMessage(printFormatUtil.printTitle(aname)+"\n");
			mService.printSize(2);
			sendMessage(printFormatUtil.printTitleMax(shoushuofangshi)+"\n");
//			sendMessage("      "+shoushuofangshi+"\n");
			sendMessage(printFormatUtil.printTitleMax("前厅第"+dayno+"单")+"\n");
//			sendMessage("   前厅第"+dayno+"单"+"\n");
			mService.print(3);	
			sendMessage(printFormatUtil.printTitle("*****************************")+ "\n");
			 sendMessage("名称" + "          "+"数量" + "      "+"价格"+" \n");
			
			menuMsgMap.put("", gonds);
			sendMessage(printFormatUtil.printMenuMSG(menuMsgMap));
			SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			String date = sDateFormat.format(new java.util.Date());
			sendMessage("数量：" + shuliang+"份"+"   ");
			sendMessage("  配送费：" + fee +"元"+ " \n");
			sendMessage("总价：" + heji +"元"+pname+youhuiquan+ " \n");
			sendMessage("备注：" + note+ " \n");
//			sendMessage("日期：" +date+ "\n");
			sendMessage("订单编号："+orderno+" \n");
			sendMessage("下单时间："+order_time+" \n");
			sendMessage("取餐时间："+receive_time+" \n");
			sendMessage("姓名："+name+" \n");
			sendMessage("联系电话："+phone+" \n");			
			sendMessage("配送地址："+address+" \n");
			sendMessage("发票抬头："+(TextUtils.isEmpty(invoice)?"无":invoice)+" \n");
//			sendMessage("信用代码："+(TextUtils.isEmpty(mcode)?"无":mcode)+" \n");
			
			sendMessage(printFormatUtil.printTitle("*****************************")+"\n");
			sendMessage(printFormatUtil.printTitle("请妥善保管好购物凭证"+"\n"));
			sendMessage(printFormatUtil.printTitle("谢谢惠顾！")+ "\n");
			sendMessage(" \n");
			sendMessage(" \n");
			sendMessage(" \n");
			sendMessage(" \n");
			sendMessage(" \n");
			sendMessage(" \n");
			break;
		case R.id.print_img_btn:
        	sendMessage("\n");
        	sendMessage("\n");
        	
        	BufferedInputStream bis = null;
			try {
				bis = new BufferedInputStream(getAssets()
					      .open("android.jpg"));
			} catch (IOException e) {
				e.printStackTrace();
			}
			Bitmap bitmap = BitmapFactory.decodeStream(bis);
			
        	sendMessage(bitmap);
        	
        	sendMessage(" \n");
        	sendMessage(" \n");
        	sendMessage(" \n");
			break;
		case R.id.print_connect_btn:
//			openOptionsMenu();
			 Intent serverIntent = new Intent(this, DeviceListActivity.class);
	         startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
			break;
		case R.id.print_out_btn:
			sendMessage(" \n");
			break;
		}
	}
	
	
    /**
     * 打印
     * @param message
     */
	private void sendMessage(String message) {

		if (message.length() > 0) {
			// Get the message bytes and tell the BluetoothService to write
			byte[] send;
			try {
				send = message.getBytes("GB2312");
			} catch (UnsupportedEncodingException e) {
				send = message.getBytes();
			}

			mService.write(send);
		}
	}
	
	
	private void sendMessage(Bitmap bitmap) {
		// Check that we're actually connected before trying anything
		if (mService.getState() != BluetoothService.STATE_CONNECTED) {
			Toast.makeText(this, "蓝牙没有连接", Toast.LENGTH_SHORT).show();
			return;
		}
		// 发送打印图片前导指令
		byte[] start = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B,
				0x40, 0x1B, 0x33, 0x00 };
		mService.write(start);
		
		/**获取打印图片的数据**/
//		byte[] send = getReadBitMapBytes(bitmap);
		
		mService.printCenter();
		byte[] draw2PxPoint = PicFromPrintUtils.draw2PxPoint(bitmap);
		
		mService.write(draw2PxPoint);
		// 发送结束指令
		byte[] end = { 0x1d, 0x4c, 0x1f, 0x00 };
		mService.write(end);
	}
	
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                // Get the device MAC address
                String address = data.getExtras()
                                     .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                // Attempt to connect to the device
                mService.connect(device);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
//                setupChat();
            	Toast.makeText(this, "蓝牙已打开", 0);
            } else {
            	Toast.makeText(this, "蓝牙没有打开", 0);
                finish();
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.scan:
            Intent serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
            return true;
        case R.id.disconnect:
        	mService.stop();
            return true;
        }
        return false;
    }
    
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                switch (msg.arg1) {
                case BluetoothService.STATE_CONNECTED:
                	print_connect_btn.setText("已连接:");
                	print_connect_btn.append(mConnectedDeviceName);
                    break;
                case BluetoothService.STATE_CONNECTING:
                	print_connect_btn.setText("正在连接...");
                	Toast.makeText(BluetoothActivity.this, "正在连接...", Toast.LENGTH_LONG).show();
                    break;
                case BluetoothService.STATE_LISTEN:
                case BluetoothService.STATE_NONE:
                	print_connect_btn.setText("无连接");
                    break;
                }
                break;
            case MESSAGE_WRITE:
                break;
            case MESSAGE_READ:
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "连接至"
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
	private Button print_connect_btn;
}
